package com.example.dollarShipping.controller;


import com.example.dollarShipping.entity.User;
import com.example.dollarShipping.security.UserDetailsImpl;
import com.example.dollarShipping.service.UserService;
import com.example.dollarShipping.utils.JwtUtils;
import com.example.dollarShipping.utils.Result;
import com.example.dollarShipping.utils.ResultCode;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController()
@RequestMapping("/auth")
public class AuthController {
	@Resource
	AuthenticationManager authenticationManager;

	@Resource
	UserService userService;


	@Resource
	PasswordEncoder passwordEncoder;

	ResultCode resultCode = new ResultCode();

	@PostMapping("/login")
	public Result authenticateUser(@Valid @RequestBody User user) {
		System.out.println("login");
		Result res = new Result();
		try {
				Authentication authentication = authenticationManager.authenticate(
						new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword()));
				JwtUtils jwtUtils = new JwtUtils();
				String jwt = jwtUtils.generateJwtToken(authentication);
				UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
				User u = userService.getDetail(userDetails.getId());
				u.setToken(jwt);
				u.setPassword(user.getPassword());
				u.setRoleId(userDetails.getRoleId());
				res.setMessage("登录成功");
				Map<String, Object> map =new HashMap<>();
				map.put("user",u);
				res.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(ResultCode.LOGINERR);
			res.setMessage(resultCode.getMsg(ResultCode.LOGINERR));
		}
		return res;
    }

	@PostMapping("/signup")
	public Result registerUser(@Valid @RequestBody User signUp) {
		Result res = new Result();
		if (userService.existsByUsername(signUp.getUserName())) {
			res.setCode(ResultCode.EXISTERR);
			res.setMessage("Error: Username is already taken!");
			return res;
		}

		if (userService.existsByEmail(signUp.getEmail())) {
			res.setCode(ResultCode.EXISTERR);
			res.setMessage("Error: Email is already in use!");
			return res;
		}
		try {
			signUp.setPassword(passwordEncoder.encode(signUp.getPassword()));
			userService.save(signUp);
			res.setMessage("用户注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(ResultCode.InfoAddERR);
			res.setMessage(resultCode.getMsg(ResultCode.InfoAddERR));
		}
		return res;
	}

	//得到用户列表
	@GetMapping("/userList")
	@PreAuthorize("hasAuthority('admin')")
	public Result getCarrierList(@RequestParam(required = false,name = "roleId") Long roleId){
		Result res = new Result();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<User> list = userService.getInfo(roleId);
			map.put("list",list);
			res.setMessage("返回成功");
			res.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(resultCode.InfoGetERR);
			res.setMessage(resultCode.getMsg(resultCode.InfoGetERR));
		}
		return res;
	}

	// 更新用户信息
	@PutMapping("/modUser")
	@PreAuthorize("hasAnyAuthority('admin','account','carrier','driver')")
	public Result modUser(@RequestBody User u){
		Result res = new Result();
		try {
			u.setPassword(passwordEncoder.encode(u.getPassword()));
			int r = userService.updateUserInfo(u);
			if(r > 0){
				res.setMessage("信息更新成功");
			}else{
				res.setCode(ResultCode.InfoModERR);
				res.setMessage(resultCode.getMsg(ResultCode.InfoModERR));
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(ResultCode.ERROR);
			res.setMessage(resultCode.getMsg(ResultCode.ERROR));
		}
		return res;
	}

	//注销用户
	@DeleteMapping("/delUser")
	@PreAuthorize("hasAnyAuthority('admin','account','carrier','driver')")
	public Result delUser(@RequestParam(required = false,name = "id") Long id){
		Result res = new Result();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			userService.delUser(id);
			res.setMessage("注销成功");
			res.setData(map);
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(resultCode.InfoDelERR);
			res.setMessage(resultCode.getMsg(resultCode.InfoDelERR));
		}
		return res;
	}
}
